const fs = require('fs-extra');
const path = require('path');
const logger = require('./logger');

class ConfigLoader {
    constructor() {
        this.config = null;
        this.initialized = false;
    }

    async load() {
        if (this.initialized) {
            return this.config;
        }

        try {
            const defaultConfigPath = path.join(__dirname, '../../config/default.json');
            const devConfigPath = path.join(__dirname, '../../config/development.json');
            
            let defaultConfig = {};
            let devConfig = {};
            
            // 加载默认配置
            if (await fs.pathExists(defaultConfigPath)) {
                defaultConfig = await fs.readJson(defaultConfigPath);
            } else {
                console.log('⚠️ 默认配置文件不存在，使用内置默认配置');
            }
            
            // 加载开发环境配置
            if (await fs.pathExists(devConfigPath)) {
                devConfig = await fs.readJson(devConfigPath);
            }
            
            // 合并配置
            this.config = {
                ...this.getDefaultConfig(), // 使用内置默认配置作为基础
                ...defaultConfig,
                ...devConfig
            };
            
            this.initialized = true;
            console.log('✅ 配置加载完成');
            
            return this.config;
        } catch (error) {
            console.error('❌ 配置加载失败:', error);
            // 返回一个基本的配置对象，避免应用崩溃
            return this.getDefaultConfig();
        }
    }

    // 内置默认配置
    getDefaultConfig() {
        return {
            server: {
                port: 8080,
                host: '0.0.0.0'
            },
            napcat: {
                baseUrl: 'http://192.168.5.4:3000',
                token: '',
                timeout: 30000
            },
            webhook: {
                path: '/webhook',
                secret: '',
                enableSignature: false
            },
            storage: {
                basePath: './data',
                images: 'images',
                voices: 'voices',
                videos: 'videos',
                files: 'files',
                texts: 'texts'
            },
            security: {
                maxFileSize: 10485760,
                allowedMimeTypes: [
                    "image/jpeg",
                    "image/png", 
                    "image/gif",
                    "audio/mpeg",
                    "video/mp4",
                    "text/plain",
                    "application/json"
                ]
            },
            firstRun: false  // 添加默认值
        };
    }

    get() {
        if (!this.initialized) {
            throw new Error('配置未加载，请先调用 load() 方法');
        }
        return this.config;
    }

    async update(newConfig) {
        try {
            const devConfigPath = path.join(__dirname, '../../config/development.json');
            await fs.writeJson(devConfigPath, newConfig, { spaces: 2 });
            this.config = { ...this.config, ...newConfig };
            console.log('✅ 配置更新成功');
            return this.config;
        } catch (error) {
            console.error('❌ 配置更新失败:', error);
            throw error;
        }
    }

    // 重新加载配置
    async reload() {
        this.initialized = false;
        this.config = null;
        return await this.load();
    }
}

module.exports = new ConfigLoader();